<template>
  <div class="page-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="客户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户姓名"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="客户状态"
          clearable
          style="width: 178px"
        >
          <el-option
            v-for="dict in dict.type.customer_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['customer:customer:add']"
          >新增客户</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['customer:customer:remove']"
          >批量删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['customer:customer:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="customerList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="ID"
        align="center"
        key="id"
        prop="id"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="头像"
        align="center"
        key="avatar"
        prop="avatar"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-image
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
            fit="cover"
            style="width: 50px; height: 50px; border-radius: 4px"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="客户姓名"
        align="center"
        key="name"
        prop="name"
        v-if="columns[2].visible"
      />
      <el-table-column
        label="手机号码"
        align="center"
        key="phone"
        prop="phone"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="性别"
        align="center"
        key="gender"
        prop="gender"
        v-if="columns[4].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_user_sex"
            :value="scope.row.gender"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="会员等级"
        align="center"
        key="levelId"
        prop="levelId"
        v-if="columns[5].visible"
      >
        <template slot-scope="scope">
          <el-tag :type="getLevelTagType(scope.row.levelId)">
            {{ getLevelName(scope.row.levelId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="积分"
        align="center"
        key="points"
        prop="points"
        v-if="columns[6].visible"
      />
      <el-table-column
        label="账户余额"
        align="center"
        key="balance"
        prop="balance"
        v-if="columns[7].visible"
      />
      <el-table-column
        label="状态"
        align="center"
        key="status"
        prop="status"
        v-if="columns[8].visible"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="2"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['customer:customer:query']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['customer:customer:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['customer:customer:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="选择生日"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户来源" prop="source">
              <el-select v-model="form.source" placeholder="请选择客户来源">
                <el-option
                  v-for="item in sourceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar" :limit="1" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会员等级" prop="levelId">
              <el-select v-model="form.levelId" placeholder="请选择会员等级">
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分" prop="points">
              <el-input-number v-model="form.points" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="账户余额" prop="balance">
              <el-input-number
                v-model="form.balance"
                :precision="2"
                :step="0.1"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户详情对话框 -->
    <el-dialog
      title="客户详情"
      :visible.sync="detailOpen"
      width="780px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{
          detail.name
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{
          detail.phone
        }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <dict-tag :options="dict.type.sys_user_sex" :value="detail.gender" />
        </el-descriptions-item>
        <el-descriptions-item label="生日">{{
          formatDate(detail.birthday)
        }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{
          detail.email
        }}</el-descriptions-item>
        <el-descriptions-item label="客户来源">{{
          getSourceName(detail.source)
        }}</el-descriptions-item>
        <el-descriptions-item label="会员等级">{{
          getLevelName(detail.levelId)
        }}</el-descriptions-item>
        <el-descriptions-item label="积分">{{
          detail.points
        }}</el-descriptions-item>
        <el-descriptions-item label="账户余额"
          >¥{{ formatAmount(detail.balance) }}</el-descriptions-item
        >
        <el-descriptions-item label="累计消费"
          >¥{{ detail.total_consumption }}</el-descriptions-item
        >
        <el-descriptions-item label="最后到店时间">{{
          formatDate(detail.last_visit_time)
        }}</el-descriptions-item>
        <el-descriptions-item label="到店次数">{{
          detail.visit_count
        }}</el-descriptions-item>
        <el-descriptions-item label="客户状态">
          <el-tag :type="detail.status === 1 ? 'success' : 'danger'">
            {{ detail.status === 1 ? "正常" : "禁用" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          detail.createdAt
        }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">头像</el-divider>
      <div class="image-container">
        <el-image
          :src="detail.avatar"
          :preview-src-list="[detail.avatar]"
          fit="cover"
          style="width: 200px; height: 200px"
        >
        </el-image>
      </div>

      <el-divider content-position="left">备注信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="备注">{{
          detail.notes
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCustomers,
  deleteCustomer,
  deleteCustomers,
  updateCustomer,
  getCustomer,
  addCustomer,
} from "@/api/customer/customer";
import { MessageBox } from "element-ui";

export default {
  name: "Customer",
  dicts: ["sys_user_sex", "customer_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户列表数据
      customerList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        phone: undefined,
        status: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `ID`, visible: true },
        { key: 1, label: `头像`, visible: true },
        { key: 2, label: `客户姓名`, visible: true },
        { key: 3, label: `手机号码`, visible: true },
        { key: 4, label: `性别`, visible: true },
        { key: 5, label: `会员等级`, visible: true },
        { key: 6, label: `积分`, visible: true },
        { key: 7, label: `账户余额`, visible: true },
        { key: 8, label: `状态`, visible: true },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        phone: undefined,
        gender: undefined,
        birthday: undefined,
        email: undefined,
        avatar: undefined,
        levelId: 0,
        points: 0,
        total_consumption: 0,
        balance: 0,
        last_visit_time: undefined,
        visit_count: 0,
        status: 1,
        source: undefined,
        notes: undefined,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "客户姓名长度必须在2到50个字符之间",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        levelId: [
          { required: true, message: "请选择会员等级", trigger: "change" },
        ],
        source: [
          { required: true, message: "请选择客户来源", trigger: "change" },
        ],
      },
      // 详情弹出层
      detailOpen: false,
      // 详情数据
      detail: {
        name: "",
        phone: "",
        gender: undefined,
        birthday: "",
        email: "",
        avatar: "",
        levelId: 0,
        points: 0,
        total_consumption: 0,
        balance: 0,
        last_visit_time: "",
        visit_count: 0,
        status: 1,
        source: "",
        notes: "",
        created_at: "",
        updated_at: "",
      },
      // 会员等级选项
      levelOptions: [
        { value: 0, label: "普通会员" },
        { value: 1, label: "银卡会员" },
        { value: 2, label: "金卡会员" },
        { value: 3, label: "钻石会员" },
      ],
      // 客户来源选项
      sourceOptions: [
        { value: "online", label: "线上注册" },
        { value: "offline", label: "线下门店" },
        { value: "referral", label: "老客户推荐" },
        { value: "advertisement", label: "广告推广" },
        { value: "other", label: "其他渠道" },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
      };
      listCustomers(params)
        .then((response) => {
          if (response.code === 200) {
            this.customerList = response.rows;
            this.total = response.total;
          } else {
            this.$modal.msgError(response.msg || "获取客户列表失败");
          }
        })
        .catch((error) => {
          console.error("获取客户列表出错：", error);
          this.$modal.msgError("获取客户列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除选中的客户数据？")
        .then(() => {
          if (row.id) {
            // 单个删除
            return deleteCustomer(row.id);
          } else {
            // 批量删除
            return deleteCustomers(this.ids.join(","));
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.detail = { ...row };
      this.detailOpen = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "customer/customers/export",
        {
          ...this.queryParams,
        },
        `customer_${new Date().getTime()}.xlsx`
      );
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getCustomer(id)
        .then((response) => {
          this.form = response;
          if (this.form.gender !== undefined && this.form.gender !== null) {
            this.form.gender = String(this.form.gender);
          }
          this.open = true;
          this.title = "修改客户";
        })
        .catch((error) => {
          console.error("获取客户详情出错：", error);
          this.$modal.msgError("获取客户详情失败，请检查网络连接或联系管理员");
        });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        phone: undefined,
        gender: undefined,
        birthday: undefined,
        email: undefined,
        avatar: undefined,
        levelId: 0,
        points: 0,
        total_consumption: 0,
        balance: 0,
        last_visit_time: undefined,
        visit_count: 0,
        status: 1,
        source: undefined,
        notes: undefined,
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updateCustomer(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "禁用";
      MessageBox.confirm('确认要"' + text + '""' + row.name + '"吗？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return updateCustomer(row);
        })
        .then(() => {
          this.$message.success(text + "成功");
        })
        .catch(() => {
          row.status = row.status === 1 ? 2 : 1;
        });
    },
    // 获取会员等级标签类型
    getLevelTagType(levelId) {
      const types = {
        0: "info",
        1: "success",
        2: "warning",
        3: "danger",
      };
      return types[levelId] || "info";
    },
    // 获取会员等级名称
    getLevelName(levelId) {
      const level = this.levelOptions.find((item) => item.value === levelId);
      return level ? level.label : "未知等级";
    },
    // 获取客户来源名称
    getSourceName(source) {
      const sourceItem = this.sourceOptions.find(
        (item) => item.value === source
      );
      return sourceItem ? sourceItem.label : "未知来源";
    },
    // 格式化金额显示
    formatAmount(amount) {
      return Number(amount).toFixed(2);
    },
    // 格式化日期显示
    formatDate(date) {
      if (!date) return "";
      return this.parseTime(date, "{y}-{m}-{d}");
    },
  },
};
</script>

<style>
.card-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-item i {
  font-size: 40px;
  margin-right: 15px;
}

.card-content {
  display: flex;
  flex-direction: column;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
}

.card-label {
  font-size: 14px;
  color: #606266;
}

.page-container {
  margin-top: 20px;
  padding: 0 20px;
}

.mb20 {
  margin-bottom: 20px;
}

.image-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-divider {
  margin: 20px 0;
}

.el-table .cell {
  white-space: nowrap;
}

.el-table .el-tag {
  margin-right: 5px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-descriptions-item__label {
  font-weight: bold;
}

.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
</style>
